import json

from collections import OrderedDict
from django.shortcuts import render
from django.utils import translation
from django.urls import reverse
from django.conf import settings
from django.shortcuts import HttpResponse, HttpResponseRedirect, render
from django.views.decorators.cache import cache_page
from django.views.decorators.http import require_GET
from hte.error.handle import abort_on_error
from hte.error.models import HTEError
from apps.base_hte.management.commands.collect_urls import URLS_RESOLVE_JS, Command as JsResolver

from .models import CarouselContent


# Create your views here.


def site_index_fsc(request):
    # lang = translation.get_language()
    # carousels = [cc.get_content(lang) for cc in
    #              CarouselContent.objects.filter(published=True).order_by('-pub_data').all()[:5]]
    return render(request, 'index.html')


# 仅开发时使用，部署时使用静态文件
@require_GET
@cache_page(5 * 60)
def get_js_resolver(req):
    js_patterns = OrderedDict()
    exclude_ns = ['admin']
    JsResolver.handle_url_module(js_patterns, settings.ROOT_URLCONF, exclude_ns)
    return HttpResponse(URLS_RESOLVE_JS + 'Urls._urls=' + json.dumps(js_patterns) + ';',
                        content_type='application/javascript')

#
# def site_help(request):
#     lang = translation.get_language()
#     try:
#         return render(request, '')


def set_language(req):
    lang = req.GET.get('lang', translation.get_language())
    if translation.check_for_language(lang):
        translation.activate(lang)
        next_page_url = req.GET.get('next', reverse('site_index'))
        response = HttpResponseRedirect(next_page_url)
        response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang)
        return response
    else:
        abort_on_error(HTEError.INVALID_LANGUAGE)
